<template>
  <view class="container">
    <view class="header">
      <view class="header-row">
        <view class="address-section" @tap="navToAddress">
          <uni-icons type="location" size="16" color="#333"></uni-icons>
          <text class="address-text">{{
            deliveryAddress || "请选择配送地址"
          }}</text>
          <uni-icons type="right" size="14" color="#999"></uni-icons>
        </view>
        <view class="order-entry" @tap="navToOrder">
          <text>我的订单</text>
          <uni-icons type="right" size="14" color="#999"></uni-icons>
        </view>
      </view>
    </view>

    <view class="category-content">
      <!-- 左侧分类菜单 -->
      <scroll-view scroll-y class="left-menu">
        <view
          v-for="(item, index) in categories"
          :key="index"
          class="menu-item"
          :class="{ active: currentCategory === index }"
          @tap="switchCategory(index)"
        >
          {{ item.name }}
        </view>
      </scroll-view>

      <!-- 右侧商品列表 -->
      <scroll-view scroll-y class="right-content" @scrolltolower="loadMore">
        <view class="goods-list">
          <view
            class="goods-item"
            v-for="(item, index) in goodsList"
            :key="index"
            @click="navToDetail(item.spuId)"
          >
            <image :src="item.mainPic" mode="aspectFill" class="goods-image" />
            <view class="goods-info">
              <text class="goods-name">{{ item.spuName }}</text>
              <text class="goods-specs">已选：{{ item.openSpec === 1 ? '请选择规格' : '单规格' }}</text>
              <view class="price-box">
                <view class="price-info">
                  <text class="current-price">¥{{ item.minPrice }}</text>
                  <text class="original-price" v-if="item.linePrice">¥{{ item.linePrice }}</text>
                </view>
                <view class="cart-action">
                  <view class="quantity-box" v-show="item.showQuantity">
                    <text class="minus" @tap.stop="updateQuantity(item, -1)">-</text>
                    <input
                      type="number"
                      v-model="item.quantity"
                      class="quantity-input"
                      @blur="handleQuantityBlur(item)"
                      @tap.stop
                    />
                    <text class="plus" @tap.stop="updateQuantity(item, 1)">+</text>
                  </view>
                  <view
                    class="cart-btn add-cart-btn"
                    @tap.stop="toggleQuantityBox(item)"
                  >
                    <uni-icons
                      type="plus"
                      size="20"
                      color="#ff4444"
                    ></uni-icons>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <uni-load-more :status="loadMoreStatus" />
      </scroll-view>
    </view>

    <!-- 添加动画小球 -->
    <view class="ball-wrap">
      <view
        class="ball"
        :style="{
          left: ballLeft + 'px',
          top: ballTop + 'px',
          display: ballShow ? 'block' : 'none',
        }"
      ></view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { categoryService, goodsService, cartService } from "@/services";
import { useCartStore } from "@/store/cartStore"; // 引入购物车 store
import { useUserStore } from "@/store/userStore"; // 引入用户 store
import { checkLoginAndRedirect } from "@/utils/auth";

// 初始化 store
const cartStore = useCartStore();
const userStore = useUserStore();

// 响应式数据定义
const currentCategory = ref(0); // 当前选中的分类索引
const categories = ref([]); // 分类列表
const goodsList = ref([]); // 商品列表
const page = ref(1); // 当前页码
const pageSize = ref(10); // 每页数量
const loadMoreStatus = ref("more"); // 加载状态
const isLoading = ref(false); // 是否正在加载
const deliveryAddress = ref(""); // 配送地址
// 购物车动画相关状态
const ballShow = ref(false); // 小球是否显示
const ballLeft = ref(0); // 小球left位置
const ballTop = ref(0); // 小球top位置
const frameIndex = ref(0); // 动画帧索引
const points = ref([]); // 动画路径点
const animationTimer = ref(null); // 动画定时器
const cartCount = ref(0); // 购物车数量

// 方法定义
// 获取分类列表
const getCategories = async () => {
  try {
    const res = await categoryService.getCategoryList();
    if (res.success && res.data) {
      categories.value = res.data;
      if (categories.value.length > 0) {
        getGoodsList();
      }
    }
  } catch (error) {
    console.error("获取分类列表失败:", error);
    uni.showToast({
      title: "获取分类失败",
      icon: "none",
    });
  }
};

// 切换分类
const switchCategory = async (index) => {
  if (currentCategory.value === index) return;
  currentCategory.value = index;
  page.value = 1;
  goodsList.value = [];
  loadMoreStatus.value = "more";
  getGoodsList();
};

// 获取商品列表
const getGoodsList = async () => {
  if (isLoading.value || loadMoreStatus.value === "noMore") return;

  isLoading.value = true;
  loadMoreStatus.value = "loading";

  try {
    const params = {
      pageIndex: page.value,
      pageSize: pageSize.value,
      categoryId: categories.value[currentCategory.value].id,
    };

    const res = await goodsService.getGoodsList(params);

    if (res.success && Array.isArray(res.data)) {
      const goodsListData = await Promise.all(res.data.map(async (item) => {
        // 获取商品详情以确定是否多规格
        const detailRes = await goodsService.getGoodsDetail(item.spuId);
        const goodsDetail = detailRes.success ? detailRes.data : null;
        
        return {
          spuId: item.spuId,
          spuName: item.title,
          mainPic: item.primaryImage,
          minPrice: item.salePrice || 0,
          linePrice: item.linePrice || 0,
          quantity: 1,
          showQuantity: false,
          // 添加规格相关信息
          openSpec: goodsDetail?.openSpec || 0,
          skus: goodsDetail?.skus || [],
          specs: goodsDetail?.specs || []
        };
      }));

      if (page.value === 1) {
        goodsList.value = goodsListData;
      } else {
        goodsList.value = [...goodsList.value, ...goodsListData];
      }

      loadMoreStatus.value = goodsList.value.length >= res.total ? "noMore" : "more";
    }
  } catch (error) {
    console.error("获取商品列表失败:", error);
    uni.showToast({
      title: "获取商品列表失败",
      icon: "none",
    });
    loadMoreStatus.value = "more";
  } finally {
    isLoading.value = false;
  }
};

// 加载更多
const loadMore = () => {
  if (loadMoreStatus.value === "more") {
    page.value++;
    getGoodsList();
  }
};

// 跳转到商品详情
const navToDetail = (spuId) => {
  uni.navigateTo({
    url: `/pages/goods/detail?spuId=${spuId}`,
  });
};

// 修改添加到购物车方法
const addToCart = async (item) => {
  // 检查登录状态
  if (!userStore.checkLogin()) {
    uni.navigateTo({
      url: `/pages/login/login?redirect=${encodeURIComponent(
        "/pages/category/category"
      )}&type=switchTab`,
    });
    return;
  }

  try {
    // 获取商品详情，检查是否是多规格商品
    const res = await goodsService.getGoodsDetail(item.spuId);
    if (!res.success) {
      throw new Error('获取商品信息失败');
    }

    const goodsDetail = res.data;
    
    // 如果是多规格商品，跳转到商品详情页
    if (goodsDetail.openSpec === 1) {
      uni.navigateTo({
        url: `/pages/goods/detail?spuId=${item.spuId}`,
      });
      return;
    }

    // 单规格商品直接加入购物车
    const cartData = {
      spuId: item.spuId,
      skuId: goodsDetail.skuId || item.spuId, // 单规格商品 skuId 可能等于 spuId
      title: item.spuName,
      primaryImage: item.mainPic,
      salePrice: item.salePrice,
      quantity: item.quantity || 1,
      selected: true,
      specs: '默认规格',
      linePrice: item.linePrice,
      unit: goodsDetail.unit,
      code: goodsDetail.code
    };

    // 调用购物车 store 的添加方法
    await cartStore.addToCart(cartData);

    // 执行添加动画
    executeAddAnimation(item);

    uni.showToast({
      title: "添加成功",
      icon: "success",
    });
  } catch (error) {
    console.error("添加到购物车失败:", error);
    uni.showToast({
      title: error.message || "添加���败",
      icon: "none",
    });
  }
};

// 添加动画执行方法
const executeAddAnimation = (item) => {
  // 获取当前商品在列表中的索引
  const itemIndex = goodsList.value.findIndex(
    (good) => good.spuId === item.spuId
  );
  if (itemIndex === -1) return;

  const query = uni.createSelectorQuery();
  Promise.all([
    new Promise((resolve) => {
      const systemInfo = uni.getSystemInfoSync();
      const tabBarHeight = 50;
      const cartIconPosition = {
        left: systemInfo.windowWidth * 0.6,
        top: systemInfo.windowHeight - tabBarHeight + 6,
        width: 16,
        height: 16,
      };
      resolve(cartIconPosition);
    }),
    new Promise((resolve) => {
      query
        .selectAll(".add-cart-btn")
        .boundingClientRect((data) => {
          const btnRect = data[itemIndex];
          resolve(btnRect);
        })
        .exec();
    }),
  ]).then(([cartRect, btnRect]) => {
    if (!cartRect || !btnRect) return;

    const start = [
      btnRect.left + btnRect.width / 2,
      btnRect.top + btnRect.height / 2,
    ];

    const end = [
      cartRect.left + cartRect.width / 2,
      cartRect.top + cartRect.height / 2,
    ];

    points.value = generatePoints(start, end);
    frameIndex.value = 0;
    ballShow.value = true;

    ballLeft.value = start[0];
    ballTop.value = start[1];

    animationTimer.value = setInterval(() => {
      if (frameIndex.value >= points.value.length) {
        clearInterval(animationTimer.value);
        ballShow.value = false;
        return;
      }

      const [x, y] = points.value[frameIndex.value];
      ballLeft.value = x;
      ballTop.value = y;
      frameIndex.value++;
    }, 16);
  });
};

// 跳转到地址页
const navToAddress = () => {
  uni.navigateTo({
    url: "/pages/address/address",
  });
};

// 跳转到订单页
const navToOrder = () => {
  uni.navigateTo({
    url: "/pages/order/order",
  });
};

// 修改切换数量选择框方法
const toggleQuantityBox = async (item) => {
  if (!userStore.checkLogin()) {
    uni.navigateTo({
      url: `/pages/login/login?redirect=${encodeURIComponent(
        "/pages/category/category"
      )}&type=switchTab`,
    });
    return;
  }

  // 检查是否是多规格商品
  try {
    const res = await goodsService.getGoodsDetail(item.spuId);
    if (!res.success) {
      throw new Error('获取商品信息失败');
    }

    const goodsDetail = res.data;
    
    // 如果是多规格商品，跳转到商品详情页
    if (goodsDetail.openSpec === 1) {
      uni.navigateTo({
        url: `/pages/goods/detail?spuId=${item.spuId}`,
      });
      return;
    }

    // 单规格商品，直接添加到购物车
    await addToCart(item);
  } catch (error) {
    console.error("获取商品信息失败:", error);
    uni.showToast({
      title: "操作失败",
      icon: "none",
    });
  }
};

// 更新商品数量
const updateQuantity = (item, delta) => {
  const newQuantity = (item.quantity || 0) + delta;
  if (newQuantity >= 1 && newQuantity <= 99) {
    item.quantity = newQuantity;
    // 更新购物车中的数量
    addToCart(item);
  } else {
    uni.showToast({
      title: newQuantity < 1 ? "数量能小于1" : "数量不能超过99",
      icon: "none",
    });
  }
};

// 处理数量输入框失焦
const handleQuantityBlur = (item) => {
  const quantity = parseInt(item.quantity);
  if (isNaN(quantity) || quantity < 1) {
    item.quantity = 1;
  } else if (quantity > 99) {
    item.quantity = 99;
    uni.showToast({
      title: "数量不能超过99",
      icon: "none",
    });
  }
  // 更新购物车中的数量
  addToCart(item);
};

// 贝塞尔曲线计算
const bezier = (t, p1, cp, p2) => {
  const [x1, y1] = p1;
  const [cx, cy] = cp;
  const [x2, y2] = p2;

  const x =
    Math.pow(1 - t, 2) * x1 + 2 * t * (1 - t) * cx + Math.pow(t, 2) * x2;
  const y =
    Math.pow(1 - t, 2) * y1 + 2 * t * (1 - t) * cy + Math.pow(t, 2) * y2;

  return [x, y];
};

// 生成动画路径点
const generatePoints = (start, end, height = 150) => {
  const points = [];
  const control = [start[0], start[1] - height];

  for (let t = 0; t <= 1; t += 1 / 30) {
    points.push(bezier(t, start, control, end));
  }

  return points;
};

// 添加价格显示计算方法
const getPriceDisplay = (item) => {
  if (item.openSpec === 1 && item.skus?.length > 0) {
    const prices = item.skus.map(sku => sku.salePrice);
    const minPrice = Math.min(...prices);
    const maxPrice = Math.max(...prices);
    return minPrice === maxPrice ? `¥${minPrice}` : `¥${minPrice}~¥${maxPrice}`;
  }
  return `¥${item.salePrice}`;
};

// 添加划线价显示计算方法
const getLinePriceDisplay = (item) => {
  if (item.openSpec === 1 && item.skus?.length > 0) {
    const prices = item.skus
      .filter(sku => sku.linePrice)
      .map(sku => sku.linePrice);
    
    if (prices.length > 0) {
      const minPrice = Math.min(...prices);
      const maxPrice = Math.max(...prices);
      return minPrice === maxPrice ? `¥${minPrice}` : `¥${minPrice}~¥${maxPrice}`;
    }
  }
  return item.linePrice ? `¥${item.linePrice}` : '';
};

// 生命周期钩子
onLoad(() => {
  getCategories();
});

onShow(() => {
  // 更新购物车角标
  cartStore.updateTabBarBadge();
});
</script>

<style lang="scss">
.container {
  height: 100vh;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
}

.category-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.left-menu {
  width: 180rpx;
  height: 100%;
  background-color: #f2f2f2;

  .menu-item {
    height: 100rpx;
    line-height: 100rpx;
    text-align: center;
    font-size: 28rpx;
    color: #333;
    border-bottom: 2rpx solid #e5e5e5;

    &.active {
      background-color: #fff;
      color: #ff4444;
      position: relative;

      &::before {
        content: "";
        position: absolute;
        left: 0;
        top: 20rpx;
        bottom: 20rpx;
        width: 8rpx;
        background-color: #ff4444;
      }
    }
  }
}

.right-content {
  flex: 1;
  height: 100%;
  background-color: #fff;

  .goods-list {
    padding: 20rpx;

    .goods-item {
      display: flex;
      padding: 20rpx;
      border-bottom: 2rpx solid #f5f5f5;

      .goods-image {
        width: 180rpx;
        height: 180rpx;
        border-radius: 8rpx;
        flex-shrink: 0;
      }

      .goods-info {
        flex: 1;
        margin-left: 20rpx;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .goods-name {
          font-size: 28rpx;
          color: #333;
          line-height: 1.4;
          height: 80rpx;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
        }

        .goods-specs {
          font-size: 24rpx;
          color: #999;
          margin: 10rpx 0;
        }

        .price-box {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: 12rpx;

          .price-info {
            display: flex;
            align-items: baseline;

            .current-price {
              font-size: 32rpx;
              color: #ff4444;
              font-weight: bold;
            }

            .original-price {
              font-size: 24rpx;
              color: #999;
              text-decoration: line-through;
              margin-left: 10rpx;
            }
          }

          .cart-action {
            display: flex;
            align-items: center;
          }
        }
      }
    }
  }
}

.header {
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-bottom: 2rpx solid #f5f5f5;

  .header-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16rpx 0;
  }

  .address-section {
    display: flex;
    align-items: center;
    flex: 1;

    .address-text {
      margin: 0 20rpx;
      font-size: 28rpx;
      color: #333;
      max-width: 400rpx;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  .order-entry {
    display: flex;
    align-items: center;
    font-size: 28rpx;
    color: #333;
    margin-left: 30rpx;
  }
}

.ball-wrap {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 999;

  .ball {
    position: fixed;
    width: 16rpx;
    height: 16rpx;
    background-color: #ff4444;
    border-radius: 50%;
    transform: translate(-50%, -50%);
    will-change: transform;
    box-shadow: 0 0 4rpx rgba(0, 0, 0, 0.2);
  }
}
</style>
